package com.ai.planttrees.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.ai.planttrees.dao.PlantMapper;
import com.ai.planttrees.dao.PlantRecordMapper;
import com.ai.planttrees.dao.RuleBodyMapper;
import com.ai.planttrees.dao.UserTreeMapper;
import com.ai.planttrees.model.Plant;
import com.ai.planttrees.model.PlantRecord;
import com.ai.planttrees.model.UserTree;
import com.ai.planttrees.service.PlantService;
import com.ai.planttrees.core.AbstractService;
import com.ai.planttrees.util.BaseUtil;
import com.ai.planttrees.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * Created by CodeGenerator on 2018/04/27.
 */
@Service
public class PlantServiceImpl extends AbstractService<Plant> implements PlantService {
    private Logger logger = LoggerFactory.getLogger(PlantServiceImpl.class);
    @Resource
    private PlantMapper plantMapper;
    @Resource
    private UserTreeMapper userTreeMapper;
    @Resource
    private PlantRecordMapper plantRecordMapper;

    /**
     * 按id查询用户种树记录
     * @param userId
     * @return
     */
    @Override
    public Result selByUserId(String userId,int page) {
        logger.info("按用户活动id查询种树记录，userId：{}",userId);
        PageHelper.startPage(page,10);
        List<Plant> plantList = plantMapper.selByUserId(userId);
        logger.info("结果：{}",plantList);
        return Result.success(new PageInfo<Plant>(plantList));
    }

    @Override
    @Transactional
    public Result addPlantRecord(PlantRecord plantRecord) {
        UserTree qu = new UserTree();
        qu.setPhone(plantRecord.getUserId());
        logger.info("根据电话查询用户,电话{}",plantRecord.getUserId());
        UserTree user = userTreeMapper.selectOne(qu);
        logger.info("结果：{}",user);
        Plant p = plantMapper.selectByPrimaryKey(plantRecord.getPlantId());
        Map map = new HashMap();
        map.put("userId",plantRecord.getUserId());
        map.put("plantType",p.getPlantType());
        logger.info("查询今日"+p.getPlantName()+"次数");
        Integer count = plantMapper.countTodayByUserId(map);
        logger.info("结果：{}",count);
        if(count!=null && count >= p.getPlantCount()){
            return Result.fail("您今天的["+p.getPlantName()+"]的次数已用完");
        }
        logger.info("查询今日最后"+p.getPlantName()+"时间");
        Date date = plantMapper.lastTimeTodayByUserId(map);
        logger.info("结果：{}",date);
        if(date!=null){
            if(new Date().getTime() < date.getTime()+ TimeUnit.MINUTES.toMillis(p.getPlantTime()-1)){
                return Result.fail("距离上次["+p.getPlantName()+"]没有超过"+p.getPlantTime()+"分钟");
            }
        }
        long l = user.getFlow()+p.getPlantFlow();//计算种树后的流量
        user.setFlow(l);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(user.getLastTime()==null){
            try {
                user.setLastTime(simpleDateFormat.parse(simpleDateFormat.format(new Date())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            user.setTreeNum(user.getTreeNum()+1);
        }else{
            long betweenDay = DateUtil.between(user.getLastTime(), new Date(), DateUnit.DAY);
            logger.info("查看几天没有种树,{}",betweenDay);
            if(betweenDay >= 1){
                try {
                    user.setLastTime(simpleDateFormat.parse(simpleDateFormat.format(new Date())));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                user.setTreeNum(user.getTreeNum()+1);
            }
        }
        int j = userTreeMapper.updateByPrimaryKeySelective(user);
        logger.info("更新用户流量{}M，结果：{}",l,j);
        plantRecord.setId(BaseUtil.getUUID());
        int i = plantRecordMapper.insertSelective(plantRecord);
        logger.info("插入"+p.getPlantName()+"记录，结果：{}",i);
        return Result.success(p.getPlantFlow());
    }

}
